/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package suministros.ejb30.temporizador;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Timer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.TimerService;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.sql.DataSource;
import suministros.ejb30.DAO.SumiEMailLocal;
import suministros.ejb30.TO.OrdenTO;
import suministros.ejb30.entity.Parametros;
import suministros.ejb30.helper.Utiles_Convertir;
import suministros.ejb30.helper.Utiles_MensajesEmail;

/**
 *
 * @author Renato
 */
@Stateless
public class AlertasSistemaScheduler implements AlertasSistemaSchedulerLocal {
     @Resource
     private TimerService ts;

     @Resource(name="jdbc/Administracion")
     DataSource dsAdministracion;

     @PersistenceUnit(unitName="suministros-pu")
     EntityManagerFactory emf;
     EntityManager em;

      @EJB
      SumiEMailLocal enviarEmail;

      @PostConstruct
      public void inicializaBean()
      {
        this.em = this.emf.createEntityManager();
      }

     @PreDestroy
      public void finalizaBean() {
        this.em.close();
      }
     /** Hora de ejecución: 23 horas */
     private static final int START_HOUR = 23;

     /** Minutos de ejecución: 0 minutos */
     private static final int START_MINUTES = 0;

     /** Segundos de ejecución: 00  */
     private static final int START_SECONDS = 0;

     /** Intervalo de la ejecución: 1440 = 24 horas */
     private static final int INTERVAL_IN_MINUTES = 60;

     private static boolean iniciar=true;
     
     public void inicializaScheduler()
    {
         if(iniciar){
             apagarTimer();

             Calendar initialExpiration = Calendar.getInstance();
             /*initialExpiration.set(Calendar.HOUR_OF_DAY, START_HOUR );
             initialExpiration.set(Calendar.MINUTE, START_MINUTES);
             initialExpiration.set(Calendar.SECOND, START_SECONDS);*/

             long intervalDuration = new Integer(INTERVAL_IN_MINUTES).longValue()*60*1000;


             ts.createTimer(initialExpiration.getTime(),intervalDuration,null);
             iniciar=false;
         }
    }

      public void apagarTimer() {
          iniciar=true;
         Collection<Timer> timers = ts.getTimers();

         if (timers != null)
         {
             for (Iterator iterator = timers.iterator(); iterator.hasNext();) {
                 Timer t = (Timer) iterator.next();
                 t.cancel();
             }
         }
     }
  public void actualizarTareas() throws Exception
  {
    Connection cnx = null;
    try {

      cnx = this.dsAdministracion.getConnection();
      CallableStatement csLlamada = cnx.prepareCall("{ call [dbo].[sp_sumi_actualizarAlertar]()}");
      csLlamada.execute();
    }
    catch (SQLException ex) {
      System.out.print(ex.getMessage());
    } finally {
      try {
        cnx.close();
      } catch (Exception ex) {
        Logger.getLogger(AlertasSistemaScheduler.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
  public List<Parametros> getListaParametrosLike(String id) throws Exception {
    Query consulta = this.em.createNativeQuery("Select * from parametros where id_parametro= '" + id + "'", Parametros.class);
    return consulta.getResultList();
  }

  public void actualizarEnvioEmail(){
       Parametros para= new Parametros();
        try {
             para = getListaParametrosLike("SU3").get(0);
             String emails= para.getParamTextoLargo();
             String tabla=Utiles_MensajesEmail.getTablaOrdenes(obtenerOrdenesGeneradas());
             Map parametros= new HashMap();
             parametros.put("cabecera",Utiles_MensajesEmail.ASUNTO_NUEVAS_ORDENES_GENERADAS );
             parametros.put("tabla", tabla);
             String body=Utiles_MensajesEmail.getBody(parametros);
             enviarEmail.enviarEmail(emails, Utiles_MensajesEmail.ASUNTO_NUEVAS_ORDENES_GENERADAS, body );
        } catch (Exception ex) {
            Logger.getLogger(AlertasSistemaScheduler.class.getName()).log(Level.SEVERE, null, ex);
        }
        

  }
  public List<OrdenTO> obtenerOrdenesGeneradas(){
      Query consulta= this.em.createNativeQuery("select nro_orden, o.cod_proveedor, razon_social, convert(char(10),fecha_emision,103), valor_total from orden  o inner join proveedor p on  o.cod_proveedor=p.cod_proveedor where year(fecha_emision)=year(getDate()) and  month(fecha_emision)=month(getDate()) and  day(fecha_emision)=day(getDate())");
      //Query consulta= this.em.createNativeQuery("select nro_orden, razon_social,  convert(char(10),fecha_emision,103), valor_total from orden  o inner join proveedor p on  o.cod_proveedor=p.cod_proveedor");
      List<OrdenTO> ordenes = Utiles_Convertir.convertirToBeanBinding_Orden(consulta.getResultList());
      return ordenes;
  }

     @Timeout
     public void execute(Timer timer)
     {
         iniciar=false;        
        try {
            actualizarTareas();
            //actualizarEnvioEmail();
        } catch (Exception ex) {
            Logger.getLogger(AlertasSistemaScheduler.class.getName()).log(Level.SEVERE, null, ex);
        }
     }
}
